

import java.util.Scanner;

/**
 * 观察内存可见性现象
 *
 * @Author 比特就业课
 * @Date 2023-01-06
 */
public class Demo_501 {

    private static class Counter {
        public static volatile int count = 0;
    }
    public static void main(String[] args) {

        Thread t1 = new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + " 线程启动");
            while (Counter.count == 0) {
                // 一直循环
            }
            System.out.println(Thread.currentThread().getName() + " 线程退出");
        }, "t1");
        // 启动线程
        t1.start();

        // 确保t1先启动
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Thread t2 = new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + " 线程启动");
            // 获取用户输入
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入一个非零的值：");
            Counter.count = scanner.nextInt();

            System.out.println(Thread.currentThread().getName() + " 线程退出");

        }, "t2");
        // 启动线程
        t2.start();
    }
}
